﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Configuration;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Net;
using System.Xml;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using Guifreaks.NavigationBar;
using Guifreaks.Common;



///  15.11.2008 - adaugat in toolbar butonul de tiparire
///  
namespace ERPStudio
{
    public partial class FrmMainMdi : Form
    {
        private Guid _userId = Guid.Empty;
        private String _userName = String.Empty;
        private bool m_bLayoutCalled = false;
        public List<eInfoModule> listaModule = new List<eInfoModule>();
        private Autorizare oAuth = new Autorizare();
        private Boolean autentifica = false;
        private IntPtr HandleMDiClient;

        public Int16 CodUnitate = -1;
        public String NumeUnitate = String.Empty;
        public string TemaCurenta = String.Empty;
        public Boolean disableUpdate = false;
        /// <summary>
        /// Lista tuturor utilizatorilor din aplicatie folosita la afisarea
        /// celui care a trimis mail
        /// Se incarca in functia LoadMail
        /// </summary>
        private Dictionary<Guid, String> UserList = new Dictionary<Guid, String>();

        public FrmMainMdi()
        {
            InitializeComponent();
            LoadCfg();
            LoadDefaultMenu(); 
            AddDefaultMenu();
            SetBackGroundColorOfMDIForm();
            KeyPreview = true;
         }
        /// <summary>
        /// seteaza culoarea background-ului la fereastra principala
        /// </summary>
        private void SetBackGroundColorOfMDIForm()
        {
            foreach (Control ctl in this.Controls)
            {
                if ((ctl) is MdiClient)
                {
                    ctl.BackColor = Color.SlateGray;
                    HandleMDiClient = ctl.Handle;
                }
            }

        }

        private void MdiMainForm_Shown(object sender, EventArgs e)
        {
            MyTrace("o-->MdiMainForm_Shown");
            if (m_bLayoutCalled == false)
            {
                m_bLayoutCalled = true;
                if (SplashFrm.SplashForm != null)
                {
                    SplashFrm.CheckForIllegalCrossThreadCalls = false;
                    SplashFrm.SplashForm.Owner = this;
                }
                this.Activate();
                
            }
                    
            
            ActiveControl = meniuAplicatie;
            MyTrace("o-->GetUnitateImplicita with ESRPConnectionString");
            if (GetUnitateImplicita("ESRPConnectionString", null) == -1)
            {
                SplashFrm.CloseForm();
                Close();
                return;
            }
            MyTrace("o-->ChangeCurrentUnit");
            ChangeCurrentUnit(CodUnitate, NumeUnitate);
            MyTrace("o-->AutentificareAplicatie");
            AutentificareAplicatie(this, null);
            MyTrace("o-->LoadAllUsersFormMailCombo");
            LoadAllUsersFormMailCombo();
            MyTrace("<--oMdiMainForm_Shown");
            SplashFrm.CloseForm();
        }

        private void DemandPermission(IPermission permission)
        {
            permission.Demand();
        }

        #region Suport Mail
        private void LoadMail()
        {
            MessageLV.View = View.Details;
           //listView1.LabelEdit = true;
            MessageLV.AllowColumnReorder = true;
            //listView1.CheckBoxes = true;
            MessageLV.FullRowSelect = true;
            MessageLV.GridLines = true;
            //listView1.DoubleClick -= new EventHandler(MesajTSB_Click);
            //listView1.Sorting = SortOrder.Ascending;
            // Create columns for the items and subitems.
            MessageLV.Columns.Add("Subiect", 400, HorizontalAlignment.Left);
            MessageLV.Columns.Add("Expeditor", 200, HorizontalAlignment.Left);
            MessageLV.Columns.Add("Data", 150, HorizontalAlignment.Left);
            //listView1.Columns.Add("Citit", 100, HorizontalAlignment.Left);
        }

        private void LoadAllUsersFormMailCombo()
        {
            SqlConnection conn = StudioForm.DeschideConexiune("AdminConnectionString");

            if (conn != null)
            {
                SqlCommand cmd = new SqlCommand("SELECT [UserId],[UserName] FROM [aspnet_Users]", conn);
                SqlDataReader da = cmd.ExecuteReader();
                while (da.Read())
                {

                    UserList.Add(new Guid(da["UserID"].ToString()), da["UserName"].ToString());
                }
                da.Close();
                StudioForm.InchideConexiune(conn);
            }
        }

        private void VerificaMail(Boolean clear)
        {
            if (MesajTSB.Visible == false)
                return;
            if (clear)
                MessageLV.Items.Clear();
            SqlConnection conn = StudioForm.DeschideConexiune("ESRPConnectionString");
            if (conn == null)
            {
                Application.Exit();
                Application.ExitThread();
                return;
            }
            SqlCommand cmd = new SqlCommand("SELECT [IdMesaj],[UserDest],[UserExp],[Subiect],[DataExp],[DataCitirii] FROM [Mesaje] WHERE [UserDest]='" + _userId.ToString() + "' ORDER BY [DataExp] DESC",
                conn);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                if (MessageLV.Items.Find(dr["IdMesaj"].ToString(), true).Length == 0)
                {
                    ListViewItem item1 = new ListViewItem(dr["Subiect"].ToString(), 0);
                    // Place a check mark next to the item.
                    String nume = String.Empty;
                    UserList.TryGetValue(new Guid(dr["UserExp"].ToString()),out nume);
                    item1.SubItems.Add(nume);
                    item1.SubItems.Add(dr["DataExp"].ToString());
                    item1.SubItems.Add("on");
                    item1.Name = dr["IdMesaj"].ToString();
                    item1.Tag = dr["DataCitirii"];
                    if (item1.Tag == DBNull.Value)
                        item1.Font = new Font(item1.Font, FontStyle.Bold);

                    MessageLV.Items.Add(item1);
                }
            }
            dr.Close();
            StudioForm.InchideConexiune(cmd.Connection);

        }

       
        private void MesajTSB_Click(object sender, EventArgs e)
        {
            Assembly asm = this.GetModule("erpforms");
            if (asm == null)
                return;

            String numeClasa = "ERPForms.MesajeFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { _userId, null, null, true }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;

                newFrm.MdiParent = this;
                newFrm.Show();
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            VerificaMail(false);
        }

        private void CitesteMail(object sender, EventArgs e)
        {
            if (MessageLV.SelectedItems.Count != 0)
            {
                if(MessageLV.SelectedItems[0].SubItems[3].Text=="on")
                {
                    MessageLV.SelectedItems[0].SubItems[3].Text = "off";
                    if (MessageLV.SelectedItems[0].Tag == DBNull.Value)
                        MessageLV.SelectedItems[0].Font = new Font(MessageLV.SelectedItems[0].Font, FontStyle.Regular);

                    Assembly asm = this.GetModule("erpforms");
                    if (asm == null)
                        return;

                    String numeClasa = "ERPForms.MesajeFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                           new object[] { _userId, MessageLV.SelectedItems[0], null, false, Convert.ToInt32(MessageLV.SelectedItems[0].Name) }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;

                        newFrm.MdiParent = this;
                        newFrm.Show();
                    }





                    SqlCommand cmd= new SqlCommand("UPDATE [Mesaje] SET [DataCitirii] = getdate() WHERE [IDMesaj]=" +
                        Convert.ToInt32(MessageLV.SelectedItems[0].Name).ToString(), StudioForm.DeschideConexiune("ESRPConnectionString"));
                    cmd.ExecuteScalar();
                    StudioForm.InchideConexiune(cmd.Connection);
                    
                }
            }
        }

        #endregion

        private void LoadCfg()
        {
            MyTrace("o--> Start LoadCfg");
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
            
            SystemWebSectionGroup systemWeb = null;
            try
            {
                systemWeb = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;
            
            ConfigurationSection section = config.GetSection("connectionStrings");

            if (section.SectionInformation.IsProtected)
            {
                try
                {
                    section.SectionInformation.UnprotectSection();
                }
                catch (Exception)
                {
                    config.Sections.Remove("connectionStrings");
                }
            }
            Boolean saveStrings = false;
            String cfgString = @"Data Source=localhost;Initial Catalog = ESRP; User ID=Admin;Password=Password2009;Net=dbmslpcn;Connection Timeout=15;";
            //nu exista nici un connection string
            if (config.ConnectionStrings.ConnectionStrings["AdminConnectionString"] == null)
            {
                config.ConnectionStrings.ConnectionStrings.Add(
                    new ConnectionStringSettings("AdminConnectionString", cfgString));
                saveStrings = true;
            }
            if (config.ConnectionStrings.ConnectionStrings["ESRPConnectionString"] == null)
            {
                config.ConnectionStrings.ConnectionStrings.Add(
                    new ConnectionStringSettings("ESRPConnectionString", cfgString));
                saveStrings = true;
            }
            if (config.ConnectionStrings.ConnectionStrings["PersSalConnectionString"] == null)
            {
                config.ConnectionStrings.ConnectionStrings.Add(
                new ConnectionStringSettings("PersSalConnectionString", cfgString));
                saveStrings = true;
            }
            if (config.ConnectionStrings.ConnectionStrings["ERPConnectionString"] == null)
            {
                config.ConnectionStrings.ConnectionStrings.Add(
                new ConnectionStringSettings("ERPConnectionString", cfgString));
                saveStrings = true;
            }
            if (config.ConnectionStrings.ConnectionStrings["SANConnectionString"] == null)
            {
                config.ConnectionStrings.ConnectionStrings.Add(
                new ConnectionStringSettings("SANConnectionString", cfgString));
                saveStrings = true;
            }
            if (config.ConnectionStrings.ConnectionStrings["SallyConnectionString"] == null)
            {
                config.ConnectionStrings.ConnectionStrings.Add(
                new ConnectionStringSettings("SallyConnectionString", cfgString));
                saveStrings = true;
            }

            if (!section.SectionInformation.IsProtected)
            {
                try
                {
                    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                }
                catch (Exception)
                {
                    config.Sections.Remove("connectionStrings");
                }
            }

            if (saveStrings)
            {
                
                config.Save(ConfigurationSaveMode.Full);
            }

            

            Boolean salvare = false;

            if (configSettings["CurentCulture"] == null)
            {
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement("CurentCulture", ""));
                salvare = true;
            }
            else
            {
                if (configSettings["CurentCulture"].Value!=String.Empty)
                Application.CurrentCulture = 
                    new System.Globalization.CultureInfo(configSettings["CurentCulture"].Value.ToString());
            }

            if (configSettings["TemaCurenta"] == null)
            {
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement("TemaCurenta", ""));
                salvare = true;
            }
            else
            {
                TemaCurenta = configSettings["TemaCurenta"].Value.ToLower();
                if (TemaCurenta == "tribunal")
                {
                    this.Text = "Manager";
                    ButoaneTribunalTS.Visible = true;
                    ButoaneTS.Visible = false;
                }
            }

            // Save the configuration file.


            if (Application.CurrentCulture.Name != "ro-RO")
            {
                if (Application.CurrentCulture.NumberFormat.NumberDecimalSeparator == ",")
                {
                    MessageBox.Show("Aplicatia nu poate functiona cu virgula ca separator decimal!", "Eroare");
                    Application.Exit();
                }
            }



            //verifica daca exista setare care sa inhibe afisarea mesajului de versiune temporara
            if (configSettings["TempMessage"] == null)
            {
                ///daca nu exista adauga
                ///
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement("TempMessage", false.ToString()));
                salvare = true;
            }

            //versiunea bazei de date cu care lucreaza
            if (configSettings["DBVersion"] == null)
            {
                ///daca nu exista adauga
                ///
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement("DBVersion", "0"));
                salvare = true;
            }


            if (configSettings["SuportMail"] == null)
            {
                ///daca nu exista adauga
                ///
                config.AppSettings.Settings.Add(new KeyValueConfigurationElement("SuportMail", "nu"));
                // Save the configuration file.
                salvare = true;
            }
            else
            {
                String spMail = configSettings["SuportMail"].Value.ToString();
                if (spMail.ToLower() == "nu")
                {
                    InboxTSB.Visible = false;
                    MessageLV.Visible = false;
                    MesajTSB.Visible = false;
                }
                else
                {
                    InboxTSB.Visible = true;
                    MessageLV.Visible = true;
                    MesajTSB.Visible = true;
                }
                //splitContainer1.Visible = InboxTSB.Checked;

            }

            

            if (configSettings.Count == 0 ||
                (configSettings["Autentificare"] != null &&
                configSettings["Autentificare"].Value.ToString().ToLower() == false.ToString().ToLower()))
            {
                autentifica = true;
            }
            String RemoteUri = string.Empty, ManifestFile = String.Empty, ProxyServer = String.Empty;
            Int32 ProxyPort = 0;
            try
            {

                ///citeste configuratia din acelasi fisier ERPStudio.exe
                ///
                MyTrace("Read RemoteURL settings");
                if (configSettings["RemoteURL"] == null)
                {
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("RemoteURL", "http://www.datastudio.ro/Update/Demo/"));
                    salvare = true;
                }

                    RemoteUri = configSettings["RemoteURL"].Value.ToString().Trim();


                if (configSettings["ManifestFile"] == null)
                {
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("ManifestFile", "ERP.xml"));
                    salvare = true;
                }

                    ManifestFile = configSettings["ManifestFile"].Value.ToString().Trim();

                if (configSettings["ProxyServer"] == null)
                {
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("ProxyServer", ""));
                    salvare = true;
                }

                    ProxyServer = configSettings["ProxyServer"].Value.ToString().Trim();

                if (configSettings["ProxyPort"] == null)
                {
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("ProxyPort", ""));
                    salvare = true;
                }

                    if (configSettings["ProxyPort"].Value.ToString().Trim() != String.Empty)
                        ProxyPort = Convert.ToInt32(configSettings["ProxyPort"].Value.ToString());

                // Save the configuration file.

                if (configSettings["Disable"] == null)
                {
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("Disable", "Nu"));
                    salvare = true;
                }

                disableUpdate = configSettings["Disable"].Value.ToString().ToLower().Trim() == "da";


                if (configSettings["FinalizareAutomata"] == null)
                {
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("FinalizareAutomata", "Da"));
                    salvare = true;
                }

                if (salvare)
                    config.Save(ConfigurationSaveMode.Full);
                UpdateTSL.Text = "Update: ON";
                if (!disableUpdate)
                {
                    ProcessUpdate(RemoteUri, ManifestFile, ProxyServer, ProxyPort);
                }
                else
                {
                    UpdateTSL.Text = "Update: OFF";
                    UpdateTSL.ForeColor = Color.Red;
                }

            }
            catch (ConfigurationErrorsException err)
            {
                MyTrace("Eroare configurare: " + err.ToString());
            }
            catch (Exception ex)
            {
                MyTrace("Eroare la Salvare : " + ex.Message);
            }
            try
            {
                systemWeb.Membership.Providers.Clear();
                if(systemWeb.Membership.Providers.Count==0)
                {
                    MyTrace("Add ProviderSettings");
                    ProviderSettings  ps = new ProviderSettings("ERPStudioMembershipProvider","System.Web.Security.SqlMembershipProvider");
                    ps.Parameters.Add("connectionStringName","AdminConnectionString");
                    ps.Parameters.Add("enablePasswordRetrieval", "false");
                    ps.Parameters.Add("enablePasswordReset", "true");
                    ps.Parameters.Add("requiresQuestionAndAnswer", "false");
                    ps.Parameters.Add("requiresUniqueEmail", "false");
                    ps.Parameters.Add("maxInvalidPasswordAttempts", "5");
                    ps.Parameters.Add("minRequiredPasswordLength", "6");
                    ps.Parameters.Add("minRequiredNonalphanumericCharacters", "0");
                    ps.Parameters.Add("passwordAttemptWindow", "10");
                    ps.Parameters.Add("applicationName", "administrare");

                    systemWeb.Membership.Providers.Add(ps);
                }
                systemWeb.Membership.DefaultProvider = "ERPStudioMembershipProvider";
                config.Save(ConfigurationSaveMode.Full);

                MyTrace("config.Save(ConfigurationSaveMode.Full)");

                ConfigurationManager.RefreshSection("system.web");

            }

            catch (ConfigurationErrorsException err)
            {
                MyTrace("Eroare configurare: " + err.ToString());
            }
            catch (Exception ex)
            {
                MyTrace("Eroare la Salvare : " + ex.Message);
            }
            MyTrace("<--o End LoadCfg");    
        }


        private void MdiMainForm_Load(object sender, EventArgs e)
        {
            MyTrace("o-->MdiMainForm_Load");
            naviBar1.Visible = TemaCurenta != "tribunal";
            LoadMail();
            String ret = WindowsIdentity.GetCurrent().Name.ToString();
           
            StringBuilder cale = new StringBuilder((System.Environment.GetCommandLineArgs()[0]).ToString());
            cale.Replace(".exe", ".din");
            cale.Replace(".vshost", null);
            //LoadModule - incarca modulele definite in catalogul Module
            try
            {
                FileIOPermission f = new FileIOPermission(FileIOPermissionAccess.AllAccess, Directory.GetCurrentDirectory());
                try
                {
                    f.Demand();
                }
                catch (SecurityException s)
                {
                    MessageBox.Show(s.Message, "Message Demand", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    MyTrace("<--oMdiMainForm_Load");
                    return;
                }

                LoadModule();
                if (!oAuth.CitesteDin(String.Empty, listaModule))
                {
                    MyTrace("<--oMdiMainForm_Load");
                    return;
                }
            }
            catch (Exception)
            {
                //nu se da nici un mesaj se intra in modul
            }
            MyTrace("<--oMdiMainForm_Load");

        }

        public void MyTrace(String val)
        {
            if(Trace.Listeners.Count>0)
                Trace.WriteLine("[" + DateTime.Now.ToString() + "]" + val);
        }

        public void LoadMenu(ToolStripMenuItem mn, Guid appID, eInfoModule modInfo,int idParinte,TreeNode parinte)
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM [admin_ApplicationMenu] WHERE [ApplicationID]='" + appID.ToString() + "'" +
                (idParinte==0?" AND [IdMeniuParinte] IS NULL ":" AND  [IdMeniuParinte]="+idParinte.ToString())+" ORDER BY [Ordine]",
                StudioForm.DeschideConexiune("AdminConnectionString"));
            SqlDataReader dReader = cmd.ExecuteReader();
            ToolStripMenuItem mn1=null;
            TreeNode tn = null;
            while (dReader.Read())
            {
                if (dReader["Name"].ToString()=="-")
                    AddSeparator(mn);
                else
                {
                    mn1= AddDropDownItems(mn, dReader["Name"].ToString(), dReader["Tag"].ToString(), dReader["HandlerName"].ToString(), modInfo,parinte,out tn);   
                    LoadMenu(mn1,appID,modInfo,Convert.ToInt32(dReader["IDMeniuAplicatie"]),tn);
                }
            }
            if (!dReader.HasRows && !mn.Owner.IsDropDown)
            {
                MyTrace("Meniul " + mn.ToString() + " nu are submeniuri in baza de date");
            }
            dReader.Close();
            StudioForm.InchideConexiune(cmd.Connection);
        }

        public ToolStripMenuItem AddDropDownItems(ToolStripMenuItem parent, String Name, Object Tag, String MethodName, eInfoModule modInfo, TreeNode parinte,out TreeNode tn)
        {
            ToolStripMenuItem mn = (ToolStripMenuItem)parent.DropDownItems.Add(Name);
            mn.Name = Name;
            //cream obiectul
            if (MethodName != String.Empty)
            {
                try
                {
                    Delegate temp = Delegate.CreateDelegate(typeof(EventHandler), modInfo.theMCObject, MethodName);
                    mn.Click += (EventHandler)temp;
                }
                catch(Exception ex)
                {
                    throw(new Exception("Obiectul: " +  modInfo.theMCObject.ToString() + " nu contine metoda:" + MethodName + "\n" + ex.Message));
                }
            }
            mn.Tag = Tag;
            tn = null;
            if (parinte != null)
            {
                tn = parinte.Nodes.Add(Name);
                if (MethodName != String.Empty)
                {
                    Delegate temp = Delegate.CreateDelegate(typeof(EventHandler), modInfo.theMCObject, MethodName);
                    tn.Tag = new TreeNodeTag((EventHandler)temp, mn);
                }
            }


            return mn;
        }

        public int AddSeparator(ToolStripMenuItem parent)
        {
            int mn = parent.DropDownItems.Add(new ToolStripSeparator());
            return mn;
        }

        public Boolean HaveAccess(String ID,Guid userId,String dllName, SqlConnection con,ref String MenuName,ref Guid AppID)
        {
            SqlCommand cmd = new SqlCommand("SELECT [MenuName],[ApplicationId] FROM [admin_UserAccessApplication] WHERE [IDIntern]=" + ID + " AND [UserId]='" +
                userId.ToString() +"'", con);
            if (con == null || con.State != ConnectionState.Open)
                return false;
            SqlDataReader ret = cmd.ExecuteReader();
            Boolean este = (ret!=null) && (ret.HasRows);
            
            if(este)
            {
                ret.Read();
                MenuName = ret["MenuName"].ToString();
                AppID = (Guid)(ret["ApplicationId"]);
                ret.Close();
                cmd.CommandText = "UPDATE [aspnet_Applications] SET [NumeDLL]='" + dllName + "' WHERE [IDIntern]=" + ID; 
                cmd.ExecuteNonQuery();
            }
            if (!ret.IsClosed)
                ret.Close();
            return este;
        }
        /// <summary>
        /// incarca modulele definite in catalogul Module
        /// </summary>
        private void LoadModule()
        {
            //verifica existenta directorului Module
            string catCurent = Directory.GetCurrentDirectory();
            string catModule = catCurent + @"\Module";
            DirectoryInfo catInfo = new DirectoryInfo(catModule);
            try
            {
                //creaza directorul unde se afla modulele
                //daca nu exista
                if(!Directory.Exists(catModule))
                {
                    catInfo = Directory.CreateDirectory(catModule);
                    MyTrace(DateTime.Now.ToString() + ":Directorul " +  catInfo.FullName + " a fost creat cu succes"); 
                }
                
            }
            catch(Exception ex)
            {
                MessageBox.Show("Nu este posibila crearea directorului Module!. Cauza: " +
                    ex.Message);
                return;
            }
            listaModule.Clear();

            //incarca din acest director modulule existente
            //adica Class Library - uri
            eInfoModule aModul = null;
            String modulName = String.Empty;
            try
            {
                
                foreach (FileInfo infoFisier in catInfo.GetFiles("*.dll"))
                {
                    //pentru fiecare modul din directorul module
                    
                    modulName = infoFisier.FullName;
                    MyTrace("Load:" + modulName);
                    Assembly modAss = Assembly.LoadFile(infoFisier.FullName);
                    if (modAss == null)
                        continue;
                    aModul = new eInfoModule(modAss, infoFisier.Name, CodUnitate, NumeUnitate, TemaCurenta);
                    //verifica existenta unei clase predefinite si anume
                    if ((aModul.mModule == null) || (aModul.idModul == null))
                        continue;                    

                    //il adauga in lista daca e corespunzator
                    listaModule.Add(aModul);
                    SplashFrm.SetStatus("Modulul " + aModul.ToString() + " a fost incarcat cu succes");
                    //daca nu exista clasa asta e...

                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Eroare incarcare modul:" + modulName + " .Cauza: " +
                    ex.Message);
                MyTrace("Eroare incarcare modul:" + modulName + " .Cauza: " + ex.Message);
                return;
            }

        }

        /// <summary>
        /// verifica accesul utilizatorului pe meniu
        /// </summary>
        /// <param name="stergereMeniu"></param>
        private void CheckAccess(Boolean stergereMeniu)
        {
            if (stergereMeniu)
            {
                meniuAplicatie.Items.Clear();
                AddDefaultMenu();
            }
            SqlConnection con = StudioForm.DeschideConexiune("AdminConnectionString");
            foreach (eInfoModule aModul in listaModule)
            {
                String menuName = String.Empty;
                Guid appID = Guid.Empty;

                if ((aModul.idModul != null) && (HaveAccess(aModul.idModul.ToString(), _userId, aModul.Name, con, ref menuName, ref appID)))
                    LoadModuleMenu(aModul.mModule, menuName, appID, aModul);

                //nu trebuie eliberata memoria ca e putina
                //else
                //    aModul.ReleaseObject();
            }
            StudioForm.InchideConexiune(con);
        }

        public void SetUnitName(String numeUnitate)
        {
            UnitateTSL.Text = numeUnitate;
            UnitateTribunalTSL.Text = numeUnitate;
            CultureStatusLabel.Text = Application.CurrentCulture.Name;
        }
        /// <summary>
        /// adauga meniurile standard la meniul aplicatie
        /// </summary>
        private void AddDefaultMenu()
        {
            this.meniuAplicatie.SuspendLayout();
            this.meniuAplicatie.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fisiereToolStripMenuItem,
            this.ajutorToolStripMenuItem});
            this.meniuAplicatie.ResumeLayout(false);
            this.meniuAplicatie.PerformLayout();
        }


        private void LoadDefaultMenu()
        {
            MyTrace("o-->LoadDefaultMenu");
            this.meniuAplicatie.SuspendLayout();
            // 
            // meniuAplicatie
            // 
            this.meniuAplicatie.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
            this.meniuAplicatie.Location = new System.Drawing.Point(0, 0);
            this.meniuAplicatie.Name = "meniuAplicatie";
            this.meniuAplicatie.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
            this.meniuAplicatie.Size = new System.Drawing.Size(916, 24);
            this.meniuAplicatie.TabIndex = 0;
            this.meniuAplicatie.Text = "menuStrip1";
            // 
            // fisiereToolStripMenuItem
            // 
            this.fisiereToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.autentificareAplicatieToolStripMenuItem,
            this.autentificareToolStripMenuItem,
            this.stabilizareToolStripMenuItem,
            this.toolStripSeparator1,
            this.actualizareModuleToolStripMenuItem,
            this.toolStripSeparator2,
            this.restoreModuleToolStripMenuItem,
            this.backupModuleToolStripMenuItem,
            this.toolStripSeparator20,
            this.iesireToolStripMenuItem});
            this.fisiereToolStripMenuItem.Name = "fisiereToolStripMenuItem";
            this.fisiereToolStripMenuItem.Size = new System.Drawing.Size(50, 20);
            if(TemaCurenta=="tribunal")
                this.fisiereToolStripMenuItem.Text = "Liste";
            else
                this.fisiereToolStripMenuItem.Text = "Sistem";
            // 
            // autentificareAplicatieToolStripMenuItem
            // 
            this.autentificareAplicatieToolStripMenuItem.Name = "autentificareAplicatieToolStripMenuItem";
            this.autentificareAplicatieToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
            this.autentificareAplicatieToolStripMenuItem.Image = global::ERPStudio.Properties.Resources._001_57;
            this.autentificareAplicatieToolStripMenuItem.Text = "Autentificare aplicatie";
            this.autentificareAplicatieToolStripMenuItem.Click += new System.EventHandler(this.AutentificareAplicatie);
            // 
            // autentificareToolStripMenuItem
            // 
            this.autentificareToolStripMenuItem.Image = global::ERPStudio.Properties.Resources._001_55;
            this.autentificareToolStripMenuItem.Name = "autentificareToolStripMenuItem";
            this.autentificareToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
            this.autentificareToolStripMenuItem.Text = "Autentificare Baza Date";
            this.autentificareToolStripMenuItem.Click += new System.EventHandler(this.AutentificareBazaDate);
            // 
            // stabilizareToolStripMenuItem
            // 
            this.stabilizareToolStripMenuItem.Name = "stabilizareToolStripMenuItem";
            this.stabilizareToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
            this.stabilizareToolStripMenuItem.Text = "Stabilizare";
            this.stabilizareToolStripMenuItem.Click += new System.EventHandler(this.StabilizareModule);
            // 
            // toolStripSeparator1
            // 
            this.toolStripSeparator1.Name = "toolStripSeparator1";
            this.toolStripSeparator1.Size = new System.Drawing.Size(185, 6);
            // 
            // actualizareModuleToolStripMenuItem
            // 
            this.actualizareModuleToolStripMenuItem.Image = global::ERPStudio.Properties.Resources.web;
            this.actualizareModuleToolStripMenuItem.Name = "actualizareModuleToolStripMenuItem";
            this.actualizareModuleToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
            this.actualizareModuleToolStripMenuItem.Text = "Actualizare Module";
            this.actualizareModuleToolStripMenuItem.Click += new System.EventHandler(this.ActualizareAplicatie);
            // 
            // restoreModuleToolStripMenuItem
            // 
            this.restoreModuleToolStripMenuItem.Image = global::ERPStudio.Properties.Resources.box;
            this.restoreModuleToolStripMenuItem.Name = "restoreModuleToolStripMenuItem";
            this.restoreModuleToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
            this.restoreModuleToolStripMenuItem.Text = "Restaurare backup unitati";
            this.restoreModuleToolStripMenuItem.Click += new System.EventHandler(this.RestoreModule);
            // 
            // restoreModuleToolStripMenuItem
            // 
            this.backupModuleToolStripMenuItem.Image = global::ERPStudio.Properties.Resources._001_42;
            this.backupModuleToolStripMenuItem.Name = "restoreModuleToolStripMenuItem";
            this.backupModuleToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
            this.backupModuleToolStripMenuItem.Text = "Backup unitati";
            this.backupModuleToolStripMenuItem.Click += new System.EventHandler(this.BackupModule);

            // 
            // toolStripSeparator2
            // 
            this.toolStripSeparator2.Name = "toolStripSeparator2";
            this.toolStripSeparator2.Size = new System.Drawing.Size(185, 6);

            this.toolStripSeparator20.Name = "toolStripSeparator20";
            this.toolStripSeparator20.Size = new System.Drawing.Size(185, 6);

            // 
            // iesireToolStripMenuItem
            // 
            this.iesireToolStripMenuItem.Image = global::ERPStudio.Properties.Resources.exit_icon;
            this.iesireToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.White;
            this.iesireToolStripMenuItem.Name = "iesireToolStripMenuItem";
            this.iesireToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
            this.iesireToolStripMenuItem.Text = "Iesire";
            this.iesireToolStripMenuItem.Click += new System.EventHandler(this.IesireAplicatie);
            // 
            // ajutorToolStripMenuItem
            // 
            this.ajutorToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.ajutorToolStripMenuItem1,
            this.cumSaFacToolStripMenuItem,
            this.cautaToolStripMenuItem,
            this.cuprinsToolStripMenuItem,
            this.indexToolStripMenuItem,
            this.ajutorPreferatToolStripMenuItem,
            this.toolStripSeparator3,
            this.despreAplicatieToolStripMenuItem});
            this.ajutorToolStripMenuItem.Name = "ajutorToolStripMenuItem";
            this.ajutorToolStripMenuItem.Size = new System.Drawing.Size(49, 20);
            this.ajutorToolStripMenuItem.Text = "Ajutor";
            // 
            // ajutorToolStripMenuItem1
            // 
            this.ajutorToolStripMenuItem1.Name = "ajutorToolStripMenuItem1";
            this.ajutorToolStripMenuItem1.Size = new System.Drawing.Size(204, 22);
            this.ajutorToolStripMenuItem1.Text = "Ajutor";
            this.ajutorToolStripMenuItem1.Click += new System.EventHandler(this.HelpMe);
            // 
            // cumSaFacToolStripMenuItem
            // 
            this.cumSaFacToolStripMenuItem.Image = global::ERPStudio.Properties.Resources.questionmark_48;
            this.cumSaFacToolStripMenuItem.Name = "cumSaFacToolStripMenuItem";
            this.cumSaFacToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+F1, H";
            this.cumSaFacToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F1)));
            this.cumSaFacToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
            this.cumSaFacToolStripMenuItem.Text = "Cum sa fac...";
            this.cumSaFacToolStripMenuItem.Visible = false;
            // 
            // cautaToolStripMenuItem
            // 
            this.cautaToolStripMenuItem.Image = global::ERPStudio.Properties.Resources.search_48;
            this.cautaToolStripMenuItem.Name = "cautaToolStripMenuItem";
            this.cautaToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+F1, S";
            this.cautaToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F1)));
            this.cautaToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
            this.cautaToolStripMenuItem.Text = "Cauta";
            this.cautaToolStripMenuItem.Visible = false;
            // 
            // cuprinsToolStripMenuItem
            // 
            this.cuprinsToolStripMenuItem.Image = global::ERPStudio.Properties.Resources.app_48;
            this.cuprinsToolStripMenuItem.Name = "cuprinsToolStripMenuItem";
            this.cuprinsToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+F1, C";
            this.cuprinsToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F1)));
            this.cuprinsToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
            this.cuprinsToolStripMenuItem.Text = "Cuprins";
            this.cuprinsToolStripMenuItem.Visible = false;
            // 
            // indexToolStripMenuItem
            // 
            this.indexToolStripMenuItem.Image = global::ERPStudio.Properties.Resources.paper_content_48;
            this.indexToolStripMenuItem.Name = "indexToolStripMenuItem";
            this.indexToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+F1, I";
            this.indexToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F1)));
            this.indexToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
            this.indexToolStripMenuItem.Text = "Index";
            this.indexToolStripMenuItem.Visible = false;
            // 
            // ajutorPreferatToolStripMenuItem
            // 
            this.ajutorPreferatToolStripMenuItem.Image = global::ERPStudio.Properties.Resources.star_48;
            this.ajutorPreferatToolStripMenuItem.Name = "ajutorPreferatToolStripMenuItem";
            this.ajutorPreferatToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl+F1, F";
            this.ajutorPreferatToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F1)));
            this.ajutorPreferatToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
            this.ajutorPreferatToolStripMenuItem.Text = "Ajutor preferat";
            this.ajutorPreferatToolStripMenuItem.Visible = false;
            // 
            // toolStripSeparator3
            // 
            this.toolStripSeparator3.Name = "toolStripSeparator3";
            this.toolStripSeparator3.Size = new System.Drawing.Size(201, 6);
            // 
            // despreAplicatieToolStripMenuItem
            // 
            this.despreAplicatieToolStripMenuItem.Name = "despreAplicatieToolStripMenuItem";
            this.despreAplicatieToolStripMenuItem.Size = new System.Drawing.Size(204, 22);
            this.despreAplicatieToolStripMenuItem.Text = "Despre ERPStudio";
            this.despreAplicatieToolStripMenuItem.Click += new System.EventHandler(this.despreAplicatie);
            this.meniuAplicatie.ResumeLayout(false);
            this.meniuAplicatie.PerformLayout();
            MyTrace("<--oLoadDefaultMenu->Exit");
        }

        /// <summary>
        /// incarca meniul corespunzator modulului prin apelarea functie LoadMenu
        /// </summary>
        /// <param name="myClass"> clasa dscModule</param>
        private void LoadModuleMenu(Type myClass,String numeMenu,Guid AppID, eInfoModule modInfo)
        { 
            //apeleaza functia LoadMenu() din clasa dscModule
            MyTrace("LoadModuleMenu:" + numeMenu);
            MethodInfo myMet = myClass.GetMethod("LoadMenu", new Type[] { typeof(ToolStripMenuItem), typeof(Form), typeof(Guid), typeof(Guid) });
            MethodInfo myMetList = myClass.GetMethod("LoadMenu", new Type[] { typeof(List<ToolStripMenuItem>), typeof(Form), typeof(Guid), typeof(Guid) });
            MethodInfo myMetTree = myClass.GetMethod("LoadMenu", new Type[] { typeof(ToolStripMenuItem), typeof(Form), typeof(Guid), typeof(Guid), typeof(TreeNode)});
            MethodInfo myMetAfter = myClass.GetMethod("AfterLoadMenu", new Type[] { typeof(ToolStripMenuItem), typeof(Form), typeof(Guid), typeof(Guid) });
            MethodInfo LoadNaviBar = myClass.GetMethod("SetNaviBarInfo", new Type[] { typeof(int), typeof(TreeView) });


            List<ToolStripMenuItem> meniuriAdaugate = new List<ToolStripMenuItem>();
            TreeView meniuArbore = null;
            int idx = -1;
            TreeNode tn = null;
            if (myMet != null || myMetList != null || myMetTree != null)
            {
                ToolStripMenuItem mn = null;
                MatchCollection matches = Regex.Matches(numeMenu, @"(?<meniu>[\s|\w|\d|\.|\-]+)\s*[;]*");

                ///adauga mai multe meniuri despartite prin punct si virgula
                foreach (Match m1 in matches)
                {
                    if (m1.Success == true)
                    {
                        mn = (ToolStripMenuItem)meniuAplicatie.Items.Add(m1.Groups["meniu"].ToString());
                        mn.Text = "&" + m1.Groups["meniu"].ToString();
                        if (modInfo.StareModul == 1) //expirat
                        {
                            mn.Text = "{" + mn.Text + "}";
                            if (meniuAplicatie.Items.Count>=1)
                                meniuAplicatie.Items.Insert(1, mn);
                            return;
                        }
                        if (meniuAplicatie.Items.Count >= 1)
                            meniuAplicatie.Items.Insert(1, mn);
                        else
                            meniuAplicatie.Items.Add(mn);
                        meniuriAdaugate.Add(mn);

                        #region Adaugare modul in banda laterala
                        naviBar1.Bands.Add(new Guifreaks.NavigationBar.NaviBand());
                        idx = naviBar1.Bands.Count - 1;

                        naviBar1.Bands[idx].Text = m1.Groups["meniu"].ToString();
                        if (idx == 0)
                            naviBar1.ActiveBand = naviBar1.Bands[idx];
                        naviBar1.Bands[idx].LargeImage = GetNaviBitmap(naviBar1.Bands[idx].Text);
                        naviBar1.Bands[idx].SmallImage = GetNaviSmallBitmap(naviBar1.Bands[idx].Text);
                        meniuArbore = new TreeView();
                        meniuArbore.DoubleClick += meniuArbore_DoubleClick;
                        meniuArbore.Parent = naviBar1.Bands[idx].ClientArea;
                        meniuArbore.Dock = DockStyle.Fill;
                        tn = meniuArbore.Nodes.Add(m1.Groups["meniu"].ToString());
                        naviBar1.VisibleLargeButtons = naviBar1.Bands.Count;
                        #endregion
                    }
                }
                //
                try
                {
                    ///set navibar information
                    ///
                    if (matches.Count >= 1 && LoadNaviBar != null)
                        LoadNaviBar.Invoke(modInfo.theMCObject, new object[] { idx, meniuArbore });

                    ///varianta anterioara cand avea un singur meniu Fvdsnlasnla31031617
                    if (matches.Count == 1 && myMet != null)
                        myMet.Invoke(modInfo.theMCObject, new object[] { meniuriAdaugate[0], this, AppID, _userId });
                    if (matches.Count == 1 && myMetTree != null)
                        myMetTree.Invoke(modInfo.theMCObject, new object[] { meniuriAdaugate[0], this, AppID, _userId,tn});
                    if (matches.Count >= 1 && myMetList != null)
                        myMetList.Invoke(modInfo.theMCObject, new object[] { meniuriAdaugate, this, AppID, _userId });
                    LoadMenu(mn, AppID, modInfo,0,tn);
                    if (myMetAfter!=null)
                        myMetAfter.Invoke(modInfo.theMCObject, new object[] { mn, this, AppID, _userId });
                    if (meniuArbore != null)
                        meniuArbore.ExpandAll();

                    
                }
                catch (Exception ex)
                {
                    MyTrace(ex.ToString());
                }
            }

        }

        void meniuArbore_DoubleClick(object sender, EventArgs e)
        {
            TreeView tn = (TreeView)sender;
            if (tn != null)
            {
                TreeNode tnd = tn.SelectedNode;
                if (tnd != null)
                {
                    if (tnd.Tag == null)
                        return;
                    TreeNodeTag mn1 = (TreeNodeTag)tnd.Tag;
                    if (mn1.handler != null)
                    {
                        EventHandler h = (EventHandler)mn1.handler;
                        h(mn1.menu, null);
                    }
                }
            }
        }

        private Bitmap GetNaviBitmap(String idx)
        {
            if(idx.ToLower()=="administrare")
                    return global::ERPStudio.Properties.Resources.setting_tools;
            if(idx.ToLower()=="amix")
                return global::ERPStudio.Properties.Resources.box;
            if(idx.ToLower()=="consultatii")
                return global::ERPStudio.Properties.Resources.health;
            if(idx.ToLower()=="contabilitate")
                return global::ERPStudio.Properties.Resources.chart_curve;
            if(idx.ToLower()=="executie bugetara")
                return global::ERPStudio.Properties.Resources.chart_stock;
            if (idx.ToLower() == "parteneri")
                return global::ERPStudio.Properties.Resources.participation_rate;
            if (idx.ToLower() == "resurse umane")
                return global::ERPStudio.Properties.Resources.account_balances1;
            if (idx.ToLower() == "extensie persal")
                return global::ERPStudio.Properties.Resources.chartplotter;
            
            return global::ERPStudio.Properties.Resources.page_layout_icon_24;
        }

        private Bitmap GetNaviSmallBitmap(String idx)
        {
            if(idx.ToLower()=="administrare")
                return global::ERPStudio.Properties.Resources.setting_tools;
            if(idx.ToLower()=="amix")   
                return global::ERPStudio.Properties.Resources.box;
            if(idx.ToLower()=="consultatii")   
                return global::ERPStudio.Properties.Resources.health;
            if(idx.ToLower()=="contabilitate")   
                return global::ERPStudio.Properties.Resources.chart_curve;
            if (idx.ToLower() == "executie bugetara")   
                return global::ERPStudio.Properties.Resources.chart_stock;
            if (idx.ToLower() == "parteneri")
                return global::ERPStudio.Properties.Resources.participation_rate;
            if (idx.ToLower() == "resurse umane")
                return global::ERPStudio.Properties.Resources.account_balances1;
            if (idx.ToLower() == "extensie persal")
                return global::ERPStudio.Properties.Resources.chartplotter;
            
            return global::ERPStudio.Properties.Resources.page_layout_icon_16;
        }

        #region Handlere Butoane
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Adauga();
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Primul();
            }

        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Anterior();
            }

        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Urmator();
            }

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Ultimul();
            }

        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Card();
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Sterge();
            }

        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Cauta();
            }

        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Rezumat();
            }

        }

        private void toolStripButton9_Click_1(object sender, EventArgs e)
        {
            if (ActiveMdiChild != null && ActiveMdiChild is StudioForm)
            {
                StudioForm frm = (StudioForm)ActiveMdiChild;
                frm.Tiparire();
            }
        }
        
        #endregion

        private void AutentificareBazaDate(object sender, EventArgs e)
        {
            FrmLogin f = new FrmLogin(true, listaModule);
            f.mainFrm = this;
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                GetUnitateImplicita("ESRPConnectionString", null);
                ChangeCurrentUnit(CodUnitate, NumeUnitate);
            }
        }

        public void SetUserHost(String userName, String hostName)
        {
            tSSLHost.Text = "[" + hostName + "]";
            tSSLUser.Text = "{" + userName + "}";
        }

        public void SetArhiva(String anArhiva)
        {
            tSSLArhiva.Text = "Arhiva:" + anArhiva + "";
            if (anArhiva != String.Empty)
                tSSLArhiva.BackColor = Color.Tomato;
            else
                tSSLArhiva.BackColor = SystemColors.Control;


        }

        public Boolean EsteArhiva()
        {
            return tSSLArhiva.Text != "Arhiva:";
        }

        #region Evenimente Meniu Standard
        private void StabilizareModule(object sender, EventArgs e)
        {

            FrmStabilizare fStab = new FrmStabilizare(listaModule);
            fStab.MdiParent = this;
            fStab.Show();

        }

        private void IesireAplicatie(object sender, EventArgs e)
        {
            Close();
        }

        private void BackupModule(object sender, EventArgs e)
        {
            Assembly asm = GetModule("erpforms");
            if (asm == null)
                return;
            String numeClasa = "ERPForms.UnitatiFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { new ModuleClass()
                   {
                       workConnectionString = "ESRPConnectionString"
                   },true
                   }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;

                newFrm.MdiParent = this;
                newFrm.Show();
            }

        }

        private void RestoreModule(object sender, EventArgs e)
        {
            ///creaza catalogul Backup
            ///
            string catCurent = Directory.GetCurrentDirectory();
            string catModule = catCurent + @"\Backup";
            DirectoryInfo catInfo = new DirectoryInfo(catModule);
            try
            {
                //creaza directorul unde se afla modulele
                //daca nu exista
                if (!Directory.Exists(catModule))
                {
                    catInfo = Directory.CreateDirectory(catModule);
                    MyTrace(DateTime.Now.ToString() + ":Directorul " + catInfo.FullName + " a fost creat cu succes");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Nu este posibila crearea directorului Backup!. Cauza: " +
                    ex.Message);
                return;
            }

            Assembly asm = GetModule("erpforms");
            if (asm == null)
                return;
            String numeClasa = "ERPForms.RestoreUnitatiFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                StudioForm newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { new ModuleClass()
                   {
                       workConnectionString = "ESRPConnectionString"
                   }
                   }, Thread.CurrentThread.CurrentCulture, new object[] { }) as StudioForm;

                newFrm.MdiParent = this;
                newFrm.Show();
            }
        }

        private void ActualizareAplicatie(object sender, EventArgs e)
        {
            try
            {
                //presupunem ca nu are parametrii
                Trace.Close();
                ProcessStartInfo startInfo = new ProcessStartInfo("AutoUpdate.exe");
                startInfo.Arguments = String.Empty;                
                Process.Start(startInfo);
                if (Application.AllowQuit)
                    Application.Exit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void despreAplicatie(object sender, EventArgs e)
        {
            AboutBoxFrm frm = new AboutBoxFrm();
            frm.ShowDialog();
        }

        private void HelpMe(object sender, EventArgs e)
        {
            Help.ShowHelp(this, @".\Help\ERPStudio.chm");
        }

        private void Unitate(object sender, EventArgs e)
        {
            foreach (eInfoModule asm in listaModule)
            {
                if (asm.module.FullName.ToLower().Contains("erpforms"))
                {
                    String numeClasa = "ERPForms.UnitatiFrm";
                    Type mModule = asm.module.GetType(numeClasa);

                    if (mModule != null)
                    {
                        ModuleClass mc =new ModuleClass(CodUnitate, NumeUnitate,TemaCurenta);

                        FrmRezumat newFrm = asm.module.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                            new object[] {mc,false}, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
                        //newFrm.CodUnitate = CodUnitate;
                        newFrm.MdiParent = this;
                        newFrm.Show();
                        // se seteaza la salvare
                        //GetUnitateImplicita("ESRPConnectionString", null);
                        //ChangeCurrentUnit(CodUnitate, NumeUnitate);
                    }
                    break;
                }
            }
        }

        private void AutentificareAplicatie(object sender, EventArgs e)
        {
            MyTrace("o-->Start AutentificareAplicatie");
            meniuAplicatie.SuspendLayout();
            LoginAppFrm frm = new LoginAppFrm(listaModule);
            Boolean eAuth = false;
            if (!autentifica)
                eAuth = frm.Autentifica();
            if (autentifica || !eAuth || e != null)
                frm.ShowDialog();
            _userId = frm.AutentifiedUserID;
            _userName = frm.AutentifiedUserName;
            CheckAccess(e!=null);
            ///afiseaza meniurile incarcate
            meniuAplicatie.ResumeLayout();
            meniuAplicatie.PerformLayout();
            //meniuAplicatie.U;
            String hostName = Environment.MachineName;
            SetUserHost(_userName, hostName);
            VerificaMail(true);
            MyTrace("<--oEnd AutentificareAplicatie");
        } 
        #endregion

        public Assembly GetModule(String name)
        {
            Assembly ret=null;
            foreach (eInfoModule asm in listaModule)
            {
                if (asm.module!=null && asm.module.GetName().Name.ToLower().Contains(name.ToLower()))
                {
                    ret = asm.module;
                    if(asm.mModule==null)
                        asm.Reload(asm.Name, CodUnitate, NumeUnitate, TemaCurenta);
                    break;
                }
            }

            return ret;
        }

        public eInfoModule GetEInfoModule(String name)
        {
            eInfoModule ret = null;
            foreach (eInfoModule asm in listaModule)
            {
                if (asm.module.GetName().Name.ToLower().Contains(name))
                {
                    ret = asm;
                    break;
                }
            }
            return ret;
        }
        /// <summary>
        /// returneaza lista de metode ale unui modul
        /// </summary>
        /// <param name="name"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public DataSet GetModuleSelectMethodList(String name, ref DataSet result)
        {
            result.Tables["Metode"].Clear();
            foreach (eInfoModule asm in listaModule)
            {
                if ((name==String.Empty) || (name.ToLower().Contains(asm.module.GetName().Name.ToLower())))
                {
                    DataRow row = null;
                    if (asm.mbrInfoArray == null)
                        continue;
                    foreach (MemberInfo info in asm.mbrInfoArray)
                    {
                        row = result.Tables["Metode"].NewRow();
                        row["nume_metoda"] = info.Name;
                        result.Tables["Metode"].Rows.Add(row);
                    }
                    if(name!=String.Empty)
                        break;
                }
            }

            return result;
        }
        /// <summary>
        /// returneaza lista de module incarcate
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public DataSet GetModuleSelectList(ref DataSet result)
        {
            result.Tables["Metode"].Clear();
            foreach (eInfoModule asm in listaModule)
            {
                DataRow row = null;
                if (asm.mbrInfoArray == null)
                    continue;
                row = result.Tables["Metode"].NewRow();
                row["nume_metoda"] = asm.mModule.Module.Name;
                if (asm.idModul!=null)
                    row["idModul"] = asm.idModul.ToString();
              
                result.Tables["Metode"].Rows.Add(row);
            }

            return result;
        }

        private void ProcessUpdate(String RemoteUri,String ManifestFile,String proxyServer, Int32 proxyPort)
        {

            MyTrace("o--> Start ProcessUpdate");
            XmlDocument m_xmld = new XmlDocument(),xmlSF = new XmlDocument();
            WebClient myWebClient = new WebClient();
            /// Download manifest file
            try
            {
                WebProxy wProxy = new WebProxy();
                if (proxyServer != String.Empty)
                {
                    String addrP = proxyServer + ":" + proxyPort.ToString();
                    wProxy.Address = new Uri(addrP);
                }
                wProxy.Credentials = CredentialCache.DefaultCredentials;
                myWebClient.Proxy = wProxy;
                myWebClient.BaseAddress = RemoteUri;
                myWebClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
                MyTrace("o-->Start download " + myWebClient.BaseAddress + ManifestFile);
                myWebClient.DownloadFile(ManifestFile, ManifestFile);

                Application.DoEvents();

            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("(404)") >= 0)
                {
                    MyTrace("Lipsa fisier manifest! Verificati existenta lui cu browserul dvs. preferat!");
                    return;
                }
                if (ex.Message.IndexOf("not be resolved") >= 0)
                {
                    MyTrace("Situl actualizarilor nu poate fi contactat. Va rugam sa incercati peste 30 minute!");
                    return;
                }
                if (ex.Message.IndexOf("(1000)") >= 0)
                {
                    MyTrace(ex.Message);
                    return;
                }

                MyTrace(ManifestFile + ":\n" + ex.ToString());
                return;
            }
            XmlNodeList m_nodelist, statusFile;
            ///Load the Xml file
            m_xmld.Load(Application.StartupPath + @"\" + ManifestFile);
            //incarca starea fisierelor
            m_nodelist = m_xmld.SelectNodes("/update/name");

            XmlNode parent = m_xmld.SelectSingleNode("/update");
            DateTime dtu = DateTime.FromFileTimeUtc(Convert.ToInt64(parent.Attributes["DataPublicare"].Value));
            XmlNode parentSL = null;
            if (File.Exists(Application.StartupPath + @"\StatusFile.xml"))
            {
                xmlSF.Load(Application.StartupPath + @"\StatusFile.xml");
                statusFile = xmlSF.SelectNodes("/update/name");

                parentSL = xmlSF.SelectSingleNode("/update");
                if (parentSL.Attributes.Count != 0)
                {
                    DateTime dtl = DateTime.FromFileTimeUtc(Convert.ToInt64(parentSL.Attributes["DataPublicare"].Value));
                    MyTrace("DataSF:" + dtl.ToString() + " , DataU:" + dtu.ToString());
                    if (dtl >= dtu)
                    {
                        MyTrace("Nu este necesara updatarea programelor!");
                        return;
                    }
                    else
                    {
                        SplashFrm.CloseForm();
                        if (MessageBox.Show("Este disponibila actualizarea din data: " + dtu.ToLongDateString() + ".\nDoriti aplicarea modificarilor continute de actualizare?", "Confirmare",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        {
                            return;
                        }
                    }
                }
            }
            else
            {
                SplashFrm.CloseForm();
                if (MessageBox.Show("Este disponibila actualizarea din data: " + dtu.ToLongDateString() + ".\nDoriti aplicarea modificarilor continute de actualizare?", "Confirmare",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
            }
            ///autoupdate
            try
            {
                //presupunem ca nu are parametrii
                MyTrace("Start Proces AutoUpdate");
                Trace.Close();
                ProcessStartInfo startInfo = new ProcessStartInfo("AutoUpdate.exe");
                Process myp = Process.Start(startInfo);
                Application.Exit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            MyTrace("<--o End ProcessUpdate");

        }

        private void Inbox_Click(object sender, EventArgs e)
        {
            MessageLV.Visible = InboxTSB.Checked;
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
            // Get the connection strings section.
            KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;

            configSettings["SuportMail"].Value= InboxTSB.Checked?"da":"nu";
            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Full);
        }
        
        public Int16 GetUnitateImplicita(String workConnString, DataGridView unitatiDGV)
        {
            //MyTrace("GetUnitateImplicita");
            Int16 ret = -1;
            SqlCommand cmd = new SqlCommand("", FrmRezumat.DeschideConexiune(workConnString));
            if (cmd.Connection == null || cmd.Connection.State == ConnectionState.Closed)
                return ret;
            cmd.CommandText = "SELECT [valoare] FROM [SetariLocale] WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodSetare]='UCRT' AND [CodUnitate]=0";
            //MyTrace(cmd.CommandText);
            Object retObj = cmd.ExecuteScalar();
            if (retObj == null || retObj == DBNull.Value)
            {
                //daca nu exista inregistrare se adauga una...
                cmd.CommandText = "INSERT  INTO [SetariLocale] ([xUser],[xHost],[CodSetare],[CodUnitate],[Valoare]) VALUES(system_user,host_name(),'UCRT',0," + CodUnitate.ToString() + ")";
                //MyTrace(cmd.CommandText);
                cmd.ExecuteScalar();
                cmd.CommandText = "SELECT [valoare] FROM [SetariLocale] WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodSetare]='UCRT'";
                //MyTrace(cmd.CommandText);
                retObj = cmd.ExecuteScalar();
            }
            //MyTrace("UCRT=" + retObj.ToString());
            if (retObj != null && retObj != DBNull.Value)
            {
                CodUnitate = Convert.ToInt16(retObj);

                 cmd.CommandText = "SELECT [Denumire] FROM [Unitati] WHERE [CodUnitate]=" + CodUnitate.ToString();
                //MyTrace(cmd.CommandText);
                retObj = cmd.ExecuteScalar();
                if (retObj != null && retObj != DBNull.Value)
                {
                    NumeUnitate = retObj.ToString();
                    ret = 0;
                }
                else
                {
                    ///unitatea a fost stearsa
                    ///
                    cmd.CommandText = "UPDATE [SetariLocale] set [valoare]=0 WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodSetare]='UCRT'";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "SELECT [valoare] FROM [SetariLocale] WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodSetare]='UCRT'";
                    retObj = cmd.ExecuteScalar();
                    if (retObj != null && retObj != DBNull.Value)
                    {
                        ret = Convert.ToInt16(retObj);
                        CodUnitate = ret;
                    }
                    cmd.CommandText = "SELECT [Denumire] FROM [Unitati] WHERE [CodUnitate]=" + CodUnitate.ToString();
                    retObj = cmd.ExecuteScalar();
                    if (retObj != null && retObj != DBNull.Value)
                        NumeUnitate = retObj.ToString();
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Lipsa unitate implicita!");
                    }

                }
            }
            FrmRezumat.InchideConexiune(cmd.Connection);
            SetUnitName(NumeUnitate);

            return ret;
        }

        public void ChangeCurrentUnit(Int16 codUnit, String numeUnit)
        {
            CodUnitate = codUnit;
            foreach (eInfoModule mod in listaModule)
            {
                mod.ChangeUnit(codUnit,numeUnit);
            }
        }

        private Int16 vCop = 0;
        private void FrmMainMdi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control)
            {
                // a apasat d
                if (vCop == 0 && e.KeyValue == 68)
                    vCop = 1;
                // a apasat s
                if (vCop == 1 && e.KeyValue == 83)
                    vCop = 2;
                if (vCop == 2 && e.KeyValue == 67)
                    vCop = 3;
                if (vCop == 3)
                {
                    vCop = -1;
                    if (MessageBox.Show("Doriti stergerea unitatii curente?", "Avertisment",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {

                        foreach (eInfoModule aModul in listaModule)
                        {
                            String menuName = "Administrare";
                            Guid appID = Guid.Empty;

                            if ((aModul.idModul != null) && aModul.Name.ToLower().Contains("administrare"))
                            {
                                SqlCommand cmd = new SqlCommand("SELECT [ApplicationId],[MenuName] FROM [aspnet_Applications] WHERE [IDIntern]=" + aModul.idModul.ToString()
                                        , StudioForm.DeschideConexiune("AdminConnectionString"));
                                if (cmd.Connection.State != ConnectionState.Open)
                                    return;
                                SqlDataReader ret = cmd.ExecuteReader();
                                Boolean este = (ret != null) && (ret.HasRows);
                                if (este)
                                {
                                    ret.Read();
                                    menuName = ret["MenuName"].ToString();
                                    appID = (Guid)(ret["ApplicationId"]);
                                    ret.Close();
                                }
                                if (!ret.IsClosed)
                                    ret.Close();
                                StudioForm.InchideConexiune(cmd.Connection);
                                LoadModuleMenu(aModul.mModule, menuName, appID, aModul);
                                vCop = -1;
                                return;
                            }
                        }
                    }
                }
            }
            
            }
            
        private void UpdateTSL_Click(object sender, EventArgs e)
        {
            MessageBoxFrm mbt = new MessageBoxFrm("Verificare", "Actualizarea automată a aplicaţie este dezactivata!\nDoriti activarea ei?", String.Empty, MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                        mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
                        if (mbt.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
                        { }
        }

        private void FrmMainMdi_FormClosed(object sender, FormClosedEventArgs e)
        {
            //copiaza setarile bune
            SqlConnection con = StudioForm.DeschideConexiune("ESRPConnectionString");
            if (con != null && con.State == ConnectionState.Open)
            {
                System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
                File.Delete("ERPStudio.0.exe.config");
                config.SaveAs("ERPStudio.0.exe.config");
                StudioForm.InchideConexiune(con);
            }

        }
    }

    public class eInfoModule
    {
        public Assembly module=null;
        public MemberInfo[] mbrInfoArray = null;
        public Type mModule = null;
        public Object theMCObject = null;
        public Object idModul = null;
        public String Name = String.Empty;
        public DateTime DataInstalare = DateTime.MaxValue;
        public Int16 NrZileFunctionare=170;
        public Int16 StareModul=0; //1- gratis/expirat 2 - autorizat
        public int IDLista=0;
        public String CheieModul;


        public eInfoModule()
        {

        }

        public eInfoModule(Assembly mod,String _name,Int16 codUnit,String numeUnit,String theme)
        {
            if (mod != null)
            {
                Name = _name;
                module = mod;
                string numeClasa = module.GetName().Name + ".dscModule";
                try
                {
                    mModule = module.GetType(numeClasa);
                }
                catch (Exception ex)
                {
                    return;
                }
                if (mModule != null)
                {
                    //mbrInfoArray = mModule.GetMembers(BindingFlags.Public);
                    theMCObject = module.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.Static, null,
                        new object[] {codUnit,numeUnit,theme }, Thread.CurrentThread.CurrentCulture, new object[] { });
                    mbrInfoArray = theMCObject.GetType().GetMembers();
                    idModul = mModule.InvokeMember("GetModuleID", BindingFlags.InvokeMethod, null, theMCObject, new object[] { });
                }

                    //as ModuleClass;

            }

        }

        public void Reload(String _name, Int16 codUnit, String numeUnit, String theme)
        {
            Name = _name;

            string numeClasa = module.GetName().Name + ".dscModule";
            mModule = module.GetType(numeClasa);
            if (mModule != null)
            {
                //mbrInfoArray = mModule.GetMembers(BindingFlags.Public);
                theMCObject = module.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.Static, null,
                    new object[] { codUnit, numeUnit, theme }, Thread.CurrentThread.CurrentCulture, new object[] { });
                mbrInfoArray = theMCObject.GetType().GetMembers();
                idModul = mModule.InvokeMember("GetModuleID", BindingFlags.InvokeMethod, null, theMCObject, new object[] { });
            }
        }

        
        public void ReleaseObject()
        {
            theMCObject = null;
            mbrInfoArray = null;
            mModule = null;
            idModul = null;    
        }


        public void ChangeUnit(Int16 codUnit,String numeUnit)
        {
            if(mModule!=null)
                mModule.InvokeMember("ChangeUnit", BindingFlags.InvokeMethod, null, theMCObject, new object[] {codUnit,numeUnit});
        }

    }
}